#if !defined(_CUSTOM_LOG_SINK_H)
#define _CUSTOM_LOG_SINK_H

#pragma once

#include <spdlog/sinks/dist_sink.h>

namespace spdlog {
	namespace sinks {

template<typename Mutex>
class branch_dist_sink final : public spdlog::sinks::dist_sink<Mutex>
{
protected:
	void sink_it_(const spdlog::details::log_msg& msg) override
	{
		for (auto &sink : this->sinks_)
		{
			const auto sink_level = sink->level();
			if (sink_level == spdlog::level::err)
			{
				if (msg.level == spdlog::level::err || msg.level == spdlog::level::critical)
				{
					sink->log(msg);
				}
			}
			else if (sink_level == spdlog::level::debug)
			{
				if (msg.level == spdlog::level::debug || msg.level == spdlog::level::trace)
				{
					sink->log(msg);
				}
			}
			else if (msg.level >= sink_level)
			{
				sink->log(msg);
			}
		}
	}
};

using branch_dist_sink_mt = branch_dist_sink<std::mutex>;
using branch_dist_sink_st = branch_dist_sink<details::null_mutex>;

/*
 * Rotating csv sink based on date.
 * If truncate != false , the created file will be truncated.
 * If max_files > 0, retain only the last max_files and delete previous.
 */
template<typename Mutex, typename FileNameCalc = daily_filename_calculator>
class daily_csv_sink final : public base_sink<Mutex>
{
public:
    // create daily csv sink which rotates on given time
    daily_csv_sink(filename_t base_filename, std::string header, int rotation_hour, int rotation_minute, bool truncate = false, uint16_t max_files = 0)
        : base_filename_(std::move(base_filename))
        , rotation_h_(rotation_hour)
        , rotation_m_(rotation_minute)
        , truncate_(truncate)
        , max_files_(max_files)
        , filenames_q_()
        , header_(std::move(header))
    {
        if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59)
        {
            SPDLOG_THROW(spdlog_ex("daily_csv_sink: Invalid rotation time in ctor"));
        }

        auto now = log_clock::now();
        auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
        file_helper_.open(filename, truncate_);
        rotation_tp_ = next_rotation_tp_();

        if (!header_.empty()) {
            details::fmt_helper::append_string_view(header_, header_buf_);
            details::fmt_helper::append_string_view(details::os::default_eol, header_buf_);
            if (file_helper_.size() == 0) {
                file_helper_.write(header_buf_);
            }
        }

        if (max_files_ > 0)
        {
            filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
            filenames_q_.push_back(std::move(filename));
        }
    }

    const filename_t &filename() const
    {
        return file_helper_.filename();
    }

protected:
    void sink_it_(const details::log_msg &msg) override
    {
        auto time = msg.time;
        bool should_rotate = time >= rotation_tp_;
        if (should_rotate)
        {
            auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
            file_helper_.open(filename, truncate_);
            rotation_tp_ = next_rotation_tp_();

            if (!header_.empty()) {
                file_helper_.write(header_buf_);
            }
        }
        memory_buf_t formatted;
        base_sink<Mutex>::formatter_->format(msg, formatted);
        file_helper_.write(formatted);

        // Do the cleaning only at the end because it might throw on failure.
        if (should_rotate && max_files_ > 0)
        {
            delete_old_();
        }
    }

    void flush_() override
    {
        file_helper_.flush();
    }

private:
    tm now_tm(log_clock::time_point tp)
    {
        time_t tnow = log_clock::to_time_t(tp);
        return spdlog::details::os::localtime(tnow);
    }

    log_clock::time_point next_rotation_tp_()
    {
        auto now = log_clock::now();
        tm date = now_tm(now);
        date.tm_hour = rotation_h_;
        date.tm_min = rotation_m_;
        date.tm_sec = 0;
        auto rotation_time = log_clock::from_time_t(std::mktime(&date));
        if (rotation_time > now)
        {
            return rotation_time;
        }
        return {rotation_time + std::chrono::hours(24)};
    }

    // Delete the file N rotations ago.
    // Throw spdlog_ex on failure to delete the old file.
    void delete_old_()
    {
        using details::os::filename_to_str;
        using details::os::remove_if_exists;

        filename_t current_file = filename();
        if (filenames_q_.full())
        {
            auto old_filename = std::move(filenames_q_.front());
            filenames_q_.pop_front();
            bool ok = remove_if_exists(old_filename) == 0;
            if (!ok)
            {
                filenames_q_.push_back(std::move(current_file));
                SPDLOG_THROW(spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno));
            }
        }
        filenames_q_.push_back(std::move(current_file));
    }

    filename_t base_filename_;
    int rotation_h_;
    int rotation_m_;
    log_clock::time_point rotation_tp_;
    details::file_helper file_helper_;
    bool truncate_;
    uint16_t max_files_;
    details::circular_q<filename_t> filenames_q_;
    std::string header_;
    memory_buf_t header_buf_;
};

using daily_csv_sink_mt = daily_csv_sink<std::mutex>;
using daily_csv_sink_st = daily_csv_sink<details::null_mutex>;

	} // namespace sinks

//
// factory functions
//
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> daily_csv_logger_mt(
    const std::string &logger_name, const filename_t &filename, const std::string &header, int hour = 0, int minute = 0, bool truncate = false)
{
    return Factory::template create<sinks::daily_csv_sink_mt>(logger_name, filename, header, hour, minute, truncate);
}

template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> daily_csv_logger_st(
    const std::string &logger_name, const filename_t &filename, const std::string &header, int hour = 0, int minute = 0, bool truncate = false)
{
    return Factory::template create<sinks::daily_csv_sink_st>(logger_name, filename, header, hour, minute, truncate);
}
} // namespace spdlog

#endif
